package com.tourlaid.mamagerment.config

import com.alibaba.druid.pool.DruidDataSource
import com.github.pagehelper.PageHelper
import com.tourlaid.mamagerment.util.ConfigUtil
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.mybatis.spring.SqlSessionTemplate
import org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.annotation.EnableTransactionManagement
import java.util.*
import javax.sql.DataSource

/**
 * @author xiaoyongge
 */
@Configuration
@EnableTransactionManagement
@MapperScan("com.tourlaid.mamagerment.mapper")
class MybatisConfiguration {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "datasource.primary")
    fun dataSource(): DataSource {
        val dataSource = DruidDataSource()
        dataSource.driverClassName = ConfigUtil.get("driverClassName")
        dataSource.username = ConfigUtil.get("database.master.username")
        dataSource.password = ConfigUtil.get("database.master.password")
        dataSource.url = ConfigUtil.get("database.master.url")
        return dataSource
    }

    @Bean
    fun txManager(): PlatformTransactionManager {
        return DataSourceTransactionManager(dataSource())
    }

    @Bean
    @Throws(Exception::class)
    fun sqlSessionFactory(pageHelper: PageHelper): SqlSessionFactory {
        val sqlSessionFactoryBean = SqlSessionFactoryBean()
        sqlSessionFactoryBean.setDataSource(dataSource())
        val arr = arrayOf(pageHelper)
        sqlSessionFactoryBean.setPlugins(arr)
        val resolver = PathMatchingResourcePatternResolver()
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"))
        return sqlSessionFactoryBean.`object`
    }


    @Bean
    fun sqlSessionTemplate(sqlSessionFactory: SqlSessionFactory): SqlSessionTemplate {
        return SqlSessionTemplate(sqlSessionFactory)
    }

    @Bean
    fun pageHelper(): PageHelper {
        val pageHelper = PageHelper()
        val p = Properties()
        p.setProperty("offsetAsPageNum", "true")
        p.setProperty("rowBoundsWithCount", "true")
        p.setProperty("reasonable", "false")
        p.setProperty("dialect", "mysql")
        pageHelper.setProperties(p)
        return pageHelper
    }
}


